<?php

namespace App\Http\Controllers\DataV;

use App\Exceptions\BusinessException;
use App\Http\Controllers\Controller;
use App\Utils\ApiResponse;
use App\Utils\VerifyRequestInput;
use Carbon\Carbon;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LawDataVController extends Controller
{
    use ApiResponse, VerifyRequestInput;

    /**
     * 文章列表
     * @return Application|Factory|View|\Illuminate\Foundation\Application
     */
    public function viewPage(): Factory|View|\Illuminate\Foundation\Application|Application
    {
        $categories =  DB::connection('rds_hb')->table('category')->where('department', 1)->pluck('cate_name', 'id')->toArray();
        $collection = DB::connection('rds_hb')->table('document')->select(['id', 'cate_id', 'title', 'subtitle', 'covers', 'datetime', 'views'])
            ->where('department', 1)->where('datetime', '<=', Carbon::today()->toDateString())->orderBy('datetime', 'desc')->get();
        return view('law', ['categories' => $categories, 'collection' => $collection, 'default' => 'https://erp.toysmodel.cn:11443/storage/rbh/20250516/682610c695847.jpg']);
    }

    /**
     * 执法卡片数据
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getDashboardCardData(): JsonResponse
    {
        $department = $this->verifyId('department');
        $collection = DB::connection('rds_hb')->table('document')->selectRaw('SUM(views) AS views_total,cate_id')
            ->where('department', $department)->groupBy('cate_id')->get();
        $categoryCollection = DB::connection('rds_hb')->table('category')->where('department', $department)
            ->select('id', 'cate_name')->get();
        $list = $this->setCardDataList($collection, $categoryCollection);
        $list[] = ['text' => '投诉总数', 'value' => mt_rand(100, 1000)];
        return $this->success($list);
    }

    /**
     * 用户和订单数据汇总
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getDateSumList(Request $request): JsonResponse
    {
        $department = $this->verifyId('department');
        $date = $request->input('date');
        if (is_array($date) && count($date) == 2) {
            $startDate = Carbon::parse($date[0]);
            $endDate = Carbon::parse($date[1]);
            if ($startDate->diffInMonths($endDate) > 1)
                return $this->fail([222001, '时间间隔不能超过1个月']);
            $collection = DB::connection('rds_hb')->table('document')
                ->where('department', $department)->whereBetween('datetime', $date)
                ->select(['id', 'cate_id', 'datetime', 'views'])->get();
            return $this->success($this->getDateItemData($department, $startDate, $endDate->diffInDays($startDate), $collection));
        } else
            return $this->success();
    }

    /**
     * 设置卡片数据
     * @param $collection
     * @param $categoryCollection
     * @return array
     */
    private function setCardDataList($collection, $categoryCollection): array
    {
        $list = [];
        foreach ($collection as $item) {
            $cateItem = $categoryCollection->where('id', $item->cate_id)->first();
            $list[] = [
                'text' => $cateItem ? $cateItem->cate_name . '浏览数' : '浏览数',
                'value' => $item->views_total
            ];
        }
        return $list;
    }

    /**
     * 获取日期数据
     * @param $department
     * @param $startDate
     * @param $days
     * @param $collection
     * @return array[]
     */
    private function getDateItemData($department, $startDate, $days, $collection): array
    {
        $categories =  DB::connection('rds_hb')->table('category')->where('department', $department)->pluck('cate_name', 'id')->toArray();
        $datasets = [];
        $x = [];
        foreach ($categories as $cateId => $cateName) {
            $viewsData = [];
            for ($i = 0; $i <= $days; $i++) {
                $date = $startDate->copy()->addDays($i);
                $x[] = $date->toDateString();
                $viewsData[] = $collection->where('datetime', $date->toDateString())->where('cate_id', $cateId)->sum('views');

            }
            $datasets[] = [
                'text' => $cateName. '浏览量',
                'list' => $viewsData
            ];
        }
        return ['x' => $x, 'datasets' => $datasets];
    }
}
